<?php
class appmanageController extends adminController{
	protected $layout = "layout";
    public function __construct(){
        if (!defined('IS_LOGIN')) $this->pageError();   
        parent::__construct();
    }
	//显示app列表
	public function index(){
		foreach(getApps() as $app){
			$apps[$app]= appConfig( $app );
		}
		$this->apps = $apps;
		$this->display();
	}
	//安装
	public function install(){	
		$app = $this->getApp();
		//安装数据库
		if( is_file( BASE_PATH . 'apps/' . $app . '/install.sql' ) ) {
			model('appmanage')->installSql( BASE_PATH . 'apps/' . $app . '/install.sql' );
		}
		//移动资源目录
		if( is_dir(  BASE_PATH . 'apps/' . $app . '/' . $app ) ){
			copy_dir(BASE_PATH . 'apps/' . $app . '/' . $app, 'public/' . $app);
			del_dir(BASE_PATH . 'apps/' . $app . '/' . $app);
		}
	 	//写入配置
		if( save_config($app, array('APP_STATE'=>1)) ){
			$this->jsonMsg('安装成功！',2);
		}	
		$this->jsonMsg('安装失败！');
	}
	//卸载
	public function uninstall(){
		$app = $this->getApp();
		//删除数据库
		config(appConfig($app) );
		$tables = config('APP_TABLES');
		$sys = config('APP_SYS');
		if($sys){
			$this->jsonMsg('系统应用禁止删除');
			return;
		}
		if(!empty($tables) ){
			$tables = explode(',', $tables);
			model('appmanage')->uninstallSql( $tables );
		}
		//删除资源文件
		if( is_dir( 'public/' . $app ) ){
			del_dir( 'public/' . $app );
		}	
		//删除app文件
		del_dir(BASE_PATH . 'apps/' . $app);
		$this->jsonMsg('卸载成功',1);
	}

	//修改状态，如启用，停用
	public function state(){
		$app = $this->getApp();
		$state = intval( $_GET['state'] ) == 1 ? 1 : 2;
		save_config($app, array('APP_STATE' => $state) );
		$this->redirect(url('appmanage/index'));
	}
	//导出
	public function export(){
		$app = $this->getApp();
		$app_path = BASE_PATH . 'apps/' . $app . '/';
		//导出数据表
		config( appConfig( $app ) );
		$tables = config('APP_TABLES');
		if( !empty($tables) ){
			$tables = explode(',', $tables);
			$sql = model('appmanage')->exportSql( $tables );
			if( !empty($sql) ){
				file_put_contents(BASE_PATH . 'apps/' . $app . '/install.sql', $sql);
			}
		}
		//拷贝资源文件
		if( is_dir( 'public/' . $app ) ){
			copy_dir( 'public/' . $app, $app_path . $app);
		}
		$zip = new Zip();
		$filename = BASE_PATH . 'cache/tmp/' . $app . '.zip';
		$zip->compress($filename, $app_path,  BASE_PATH . 'apps/'); //打包压缩
		del_dir( $app_path . $app); //删除资源文件
		Http::download($filename, $app.'.zip');//下载
		@unlink($filename);//删除文件
	}

	//创建app的基本目录和文件
	public function create(){
		if($this->isPost() ){
			$app = trim($_POST['app_id']);
			$app_name = trim($_POST['app_name']);
			$app_path = BASE_PATH . 'apps/' . $app . '/' ;
			$msg = Check::rule( array(
				array(Check::must($app), '请输入应用ID'),
				array(preg_match('/^[a-z]+$/', $app), '应用ID必须为全小写字母'),
				array(Check::must($app_name), '请输入应用名称'),
				array(!is_dir($app_path), '应用已存在，请先卸载！'),
			));
			if( true !== $msg){
				$this->jsonMsg($msg);
				return;
			}
			//拷贝默认代码
			copy_dir(BASE_PATH . 'apps/' . APP_NAME . '/code/', $app_path);
			//修改控制器,模型,api
			foreach(array('controller/indexController', 'model/demoModel', 'demoApi') as $value){			
				$value = $value . '.php';
				$file = $app_path . str_replace('demo', $app, $value);
				rename($app_path . $value, $file);
				file_put_contents($file, str_replace('demo', $app, file_get_contents($file)) );
			}
			//写入配置
			if( save_config($app, array('APP_NAME' => $app_name, 'APP_VER'=> date('1.0.ymd'))) ){
				$this->jsonMsg('创建成功！',1, url('appmanage/index'));
			}	
			$this->jsonMsg('创建失败！');
		}else{
			$this->display();
			return true;
		}
	}
	//获取app
	protected function getApp(){
		$app = trim( $_GET['app'] );
		if( empty($app) ){
			$this->pageMsg('数据写入错误');
		}
		return $app;
	}
    //新版本检测
    public function update(){
    	$app = $_GET['app'];
    	$var = $_GET['var'];
    	$rel = model('appmanage')->updete($app);
    	if($rel){
    		$str = json_decode($rel);
    		if(is_null($str)){
    			$this->jsonMsg('版本服务器出错,请稍候重试。');
    		}else{
    			$new = str_replace(".","",$str->var);
    			$old = str_replace(".","",$var);
            	$new = (int)$new;
            	$old = (int)$old;
	    		if($new > $old){
	    			$this->jsonMsg($str->info,3,$str->url);
	    		}else{
	    			$this->jsonMsg($str->info);
	    		}
    		}
    	}else{
    		$this->jsonMsg('连接超时,请稍候重试。');
    	}
    }
    //授权验证
    public function vipuser(){
    	$app = $_GET['app'];
    	$url = $_GET['url'];
    	$rel = model('appmanage')->vip($app,$url);
    	if($rel){
    		$str = json_decode($rel);
    		if(is_null($str)){
    			$this->jsonMsg('认证服务器出错,请稍候重试。');
    		}else{
	    		$this->jsonMsg($str->info,3,$str->url);
    		}
    	}else{
    		$this->jsonMsg('连接超时,请稍候重试。');
    	}
    }
}